package email;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import config.CLResourceBundleManager;
public class Email{
	
	private Session session = null;
	
	public Email(){
		session = createEmailSession();
	}
	
	public Session createEmailSession(){
		
		Properties props = getEmailProperties();
	
		return getSession(props);
	}
	
	private Properties getEmailProperties(){
		Properties props = new Properties();
		props.put("mail.smtp.host", CLResourceBundleManager.getMailSmtpHost());
		props.put("mail.smtp.socketFactory.port", CLResourceBundleManager.getMailSmtpSocetFactoryPort());
		props.put("mail.smtp.socketFactory.class", CLResourceBundleManager.getMailSmtpSocketFactoryClass());
		props.put("mail.smtp.auth", CLResourceBundleManager.getMailSmtpAuth());
		props.put("mail.smtp.port", CLResourceBundleManager.getMailSmtpPort());
		return props;
	}
	
	private Session getSession(Properties props){
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(CLResourceBundleManager.getMailAccountName(),CLResourceBundleManager.getMailAccountPassword());
			}
		};
		
		Session session = Session.getDefaultInstance(props, auth);
		return session;
	}
	
	public void sendMail(String from, String to, String subject, String text)throws MessagingException{
		if (session == null ){
			session = createEmailSession();
		}
		
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
		message.setSubject(subject);
		message.setText(text);

		Transport.send(message);
	}
}
